package org.bjf.modules.sys.listenner;

import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.bjf.modules.sys.bean.ControllerResource;
import org.bjf.modules.sys.enums.Permission;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

/**
 * 所有bean初始化前后都会回调此方法
 *
 * @author bjf
 */
@Component
@Slf4j
public class LiveBeanPostProcessor implements BeanPostProcessor {

  public static Map<String, ControllerResource> PERMISSION_MAP = new HashMap<>();

  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName)
      throws BeansException {
    Class<?> clz = bean.getClass();
    Permission permission = clz.getAnnotation(Permission.class);

    //扫描所有的PerMission注解
    if (permission != null) {
      if (clz.getAnnotation(RestController.class) != null
          || clz.getAnnotation(Controller.class) != null) {
        String resSn = permission.resSn();
        if (PERMISSION_MAP.containsKey(resSn)) {
          /*log.error("权限码[{}]重复，请检查", resSn);
          System.exit(0);*/
          return bean;
        }

        ControllerResource resource = new ControllerResource()
            .setResSn(permission.resSn())
            .setDesc(permission.resDesc());

        PERMISSION_MAP.put(resSn, resource);
      }
    }

    return bean;
  }

  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    return bean;
  }
}
